<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/07
 * Time: 13:29
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\report;

use app\admin\controller\BaseController;
use app\common\model\ChannelOrders;
use app\common\model\ReportOrderDay;

/**
 * 图表
 * Class IndexController
 * @package app\admin\controller\report
 */
class IndexController extends BaseController
{
    /**
     * 天
     * @var int
     */
    protected $day;

    /**
     * 日期
     * @var string
     */
    protected $date;

    /**
     * 订单
     * @date 2021/03/25
     * @author longli
     */
    public function order()
    {
        if($this->request->isAjax())
        {
            $type = $this->request->request('type');
            $action = "order" . ucfirst($type);
            if(method_exists($this, $action))
            {
                $this->day = $this->request->request('day', 7, 'abs');
                $this->date =  date('Y-m-d', strtotime("-{$this->day}day"));
                return $this->$action();
            }
        }
        $this->assign('year', \app\common\library\Tools::getRecentYear(10));
        $this->assign('days', [3, 7, 10, 15, 30, 45, 60, 75, 90, 180, 360]);
        return $this->fetch('order');
    }

    /**
     * 统计每个月的销量
     * @date 2021/07/13
     * @author longli
     */
    private function orderMonth()
    {
        $year = $this->request->request('year', date('Y'), 'abs');
        $report = ReportOrderDay::field(["SUM(qty) total_qty", "SUM(total_price) total_price", "DATE_FORMAT(stat_date, '%Y-%m') year", "MONTH(stat_date) month"])
            ->where([
                ["ref_key", "=", "account_id"],
                ["stat_date", "gt", $year],
                ["stat_date", "lt", $year + 1],
            ])
            ->group("year")
            ->order("year")
            ->select()->toArray();
        $lastMonth = 1;
        if(!empty($report)) $lastMonth = end($report)['month'];
        if($lastMonth < 12)
        {
            $total = $lastMonth == 1 ? 0 : null;
            for($i = $lastMonth + 1; $i <= 12; $i++)
            {
                $report[] = [
                    'total_qty' => $total,
                    'total_price' => $total,
                    'year' => "{$year}-{$i}",
                    'month' => $i
                ];
            }
        }
        else if($lastMonth == 12 && count($report) != 12)
        {
            $curr = current($report)['month'];
            $temp = [];
            for($i = 1; $i < $curr; $i++)
            {
                $temp[] = [
                    'total_qty' => 0,
                    'total_price' => 0,
                    'year' => "{$year}-{$i}",
                    'month' => $i
                ];
            }
            $report = array_merge($temp, $report);
        }
        $data = [];
        foreach($report as $item)
        {
            $data['xAxis'][] = $item['month'] . '月';
            $data['series']['type'] = 'line';
            $data['series']['smooth'] = true;
            $data['series']['name'] = '订单数';
            $totalPirce = $item['total_price'] !== null ? number_format($item['total_price'], 4, '.', ',') : null;
            $data['series']['data'][] = ['value'=>$item['total_qty'], 'total_price' => $totalPirce];
        }
        $this->success('', '', ['title'=>"{$year}年销量", 'data' => $data]);
    }

    /**
     * 销量前十位
     * @date 2021/03/30
     * @author longli
     */
    private function orderTopTen()
    {
        $report = ReportOrderDay::field([
            "ref_value `sku`", "sum(qty) `qty`"
        ])->where([
            ['ref_key', 'eq', 'sku'],
            ['stat_date', 'egt', $this->date]
        ])->group('ref_value')
        ->order('qty desc')
        ->limit( 10)
        ->select();
        $data = [];
        foreach($report as $item)
        {
            $store = \app\common\model\ProductStore::getStoreBySku($item->sku);
            $data['xAxis'][] = $item->sku;
            $data['rich'][] = [
                "height" => 50,
                "width" => 50,
                "align" => 'center',
                "backgroundColor" => ["image" => $store && $store->image_url ? $store->image_url : '/static/admin/img/no-photo.png']
            ];
            $data['series']['name'] = '订单数';
            $data['series']['data'][] = intval($item->qty);
        }
        $this->success('', '', ['title'=>"{$this->day}天销量排行", 'data' => $data]);
    }

    /**
     * 订单国家占比
     * @date 2021/03/31
     * @author longli
     */
    private function orderCountry()
    {
       $report = ReportOrderDay::field([
            "ref_value `code`", "sum(qty) `qty`"
        ])->where([
            ['ref_key', 'eq', 'buyer_country_code'],
            ['stat_date', 'egt', $this->date]
        ])->group('ref_value')
            ->order('qty desc')
            ->limit( 10)
            ->select();
        $data = [];
        foreach($report as $item)
        {
            $data['series'][] = [
                'name' => $item->code,
                'value' => intval($item->qty)
            ];
        }
        $this->success('', '', ['title'=>"{$this->day}天国家销量", 'data' => $data]);
    }

    /**
     * 订单账号销售
     * @date 2021/03/31
     * @author longli
     */
    private function orderAccount()
    {
        $report = ReportOrderDay::field([
            "ref_value `account_id`", "sum(qty) `qty`"
        ])->where([
            ['ref_key', 'eq', 'account_id'],
            ['stat_date', 'egt', $this->date]
        ])->group('ref_value')
            ->order('qty desc')
            ->limit( 10)
            ->select();
        $data = [];
        foreach($report as $item)
        {
            $data['series'][] = [
                'name' => \app\common\model\Account::get($item->account_id)->username,
                'value' => intval($item->qty)
            ];
        }
        $this->success('', '', ['title'=>"{$this->day}天账号销量", 'data' => $data]);
    }

    /**
     * 订单签收率
     * @date 2021/03/31
     * @author longli
     */
    private function orderChannel()
    {
       $succ = ChannelOrders::where([
            ['track_status', 'eq', ChannelOrders::TRACK_STATUS_RECV],
            ['update_time', 'egt', $this->date]
        ])->count();
       $exce = ChannelOrders::where([
           ['track_status', 'in', [
               ChannelOrders::TRACK_STATUS_TIMEOUT,
               ChannelOrders::TRACK_STATUS_UNRECV,
               ChannelOrders::TRACK_STATUS_EXCEPTION]],
           ['update_time', 'egt', $this->date]
       ])->count();
       $data['series'][] = [
           'name' => '签收',
           'value' => $succ
       ];
        $data['series'][] = [
            'name' => '异常',
            'value' => $exce
        ];
       $this->success('', '', ['title'=>"{$this->day}天订单签收", 'data' => $data]);
    }

    /**
     * 订单总销量
     * @date 2021/03/31
     * @author longli
     */
    protected function orderSale()
    {
        $topOne = ReportOrderDay::field([
            "ref_value `sku`", "sum(total_price) `total_price`"
        ])->where([
            ['ref_key', 'eq', 'sku'],
            ['stat_date', 'egt', $this->date]
        ])->group('ref_value')
        ->order('qty desc')
        ->limit(1)->find();
        $totalSale = ReportOrderDay::where([
            ['ref_key', 'eq', 'account_id'],
            ['stat_date', 'egt', $this->date]
        ])->sum('total_price');
        $data['series'][] = [
            'name' => $topOne->sku . ' 占',
            'value' => floatval($topOne->total_price)
        ];
        $data['series'][] = [
            'name' => '总销售额',
            'value' => floatval($totalSale)
        ];
        $this->success('', '', ['title'=>"{$this->day}天总销售额", 'data' => $data]);
    }
}